package com.smartian.scan.filesearch.impl.engine;

import android.text.TextUtils;

import com.smartian.scan.filesearch.bean.PathFile;
import com.smartian.scan.filesearch.bean.SearchResult;
import com.smartian.scan.filesearch.interfaces.ISearchTaskEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileSearchTaskEngine implements ISearchTaskEngine {


    public SearchResult doInBackground(String path) {

        List<PathFile> listFile = new ArrayList<PathFile>();
        List<PathFile> dirFile = new ArrayList<PathFile>();

        if(TextUtils.isEmpty(path)){
          return new SearchResult(listFile,dirFile);
        }

        File  file = new File(path);

        if(!file.exists()) {
            return new SearchResult(listFile,dirFile);
        }

        if(file.isFile()){
            listFile.add(PathFile.build(file,path));
            return new SearchResult(listFile,dirFile);
        }

        file.setReadable(true);

        File[] childFiles = file.listFiles();
        if (childFiles == null) {
            return new SearchResult(listFile,dirFile);
        }
        for (File subFile : childFiles) {
            if (subFile.isFile()) {
                listFile.add(PathFile.build(subFile,path));
            } else {
                dirFile.add(PathFile.build(subFile,path));
            }
        }

        return new SearchResult(listFile,dirFile);

    }
}
